import axios from 'axios';
import config from './config';
import CryptoJS from 'crypto-js';

const PASSWORD_SECRET = 'password_secret_456';

const apiClient = axios.create({
  baseURL: config.API_BASE_URL,
  headers: { 'Content-Type': 'application/json' }
});

// **用户登录**
export const login = async (username, password) => {
  try {
    const encryptedPassword = CryptoJS.AES.encrypt(password, PASSWORD_SECRET).toString();

    const response = await apiClient.post('/login', {
      username,
      password: encryptedPassword
    });

    const token = response.headers['authorization'];
    const userId = response.data.userId; // 获取后端返回的用户ID
    // console.log(userId,'userId');

    if (token) {
      localStorage.setItem('token', token);
      localStorage.setItem('userId', userId); // 存储用户ID
    }

    return { success: true, userId };
  } catch (error) {
    console.error('Login API Error:', error);
    return { success: false, message: error.response?.data?.message || '登录失败' };
  }
};


// **用户注册**
export const register = async (username, email, password) => {
  try {
    const encryptedPassword = CryptoJS.AES.encrypt(password, PASSWORD_SECRET).toString();

    const response = await apiClient.post('/register', {
      username,
      email,
      password: password
    });

    return response.data; // { success: true, message: "注册成功" }
  } catch (error) {
    console.error('Register API Error:', error);
    return { success: false, message: error.response?.data?.message || '注册失败' };
  }
};
// 用户修改密码（根据 userId）
export const changePasswordApi = async (userId, oldPassword, newPassword) => {
  try {
    const response = await apiClient.post('/changePassword', {
      userId,
      oldPassword,
      newPassword
    });

    return response.data; // { success: true, message: "密码修改成功" }
  } catch (error) {
    console.error('Change Password API Error:', error);
    return {
      success: false,
      message: error.response?.data?.message || '修改密码失败'
    };
  }
};


// 获取用户数据接口
export const getUserData = async (userId) => {
  // console.log(userId, 'userIdsxsaxas');
  try {
    // 发送 GET 请求获取用户数据
    const response = await apiClient.get(`/users/${userId}`);
    // console.log(response.data, 'response');
    // 返回用户数据
    return response.data;

  } catch (error) {
    console.error('获取用户数据失败:', error);

    // 返回错误信息
    return {
      success: false,
      message: error.response?.data?.message || '获取用户数据失败',
    };
  }
};
// 获取单词数据
export const getWordsData = async () => {
  try {
    const response = await apiClient.get('/getWordsData');  // 请求 /getWordsData API
    return response.data;
  } catch (error) {
    console.error('获取单词数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取单词数据失败',
    };
  }
};

// **获取受保护数据**
export const getProtectedData = async () => {
  const token = localStorage.getItem('token');
  if (!token) {
    return { success: false, message: '未登录' };
  }

  try {
    const response = await apiClient.get('/protected', {
      headers: { Authorization: `Bearer ${token}` }
    });
    return response.data;
  } catch (error) {
    console.error('Protected API Error:', error);
    return { success: false, message: error.response?.data?.message || '请求失败' };
  }
};

// **请求未学习过的单词 (Custom Limit)**
export const getUnlearnedWords = async (userId, limit) => {
  const token = localStorage.getItem('token');

  // If the token doesn't exist, return an error
  if (!token) {
    return { success: false, message: '未登录' };
  }

  // If the limit is not a number or is less than 1, set a default limit
  if (isNaN(limit) || limit < 1) {
    limit = 10; // Default to 10 if the limit is invalid
  }

  try {
    const response = await apiClient.post('/get-unlearned-words', {
      user_id: userId,
      limit: limit
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return response.data; // Returns the list of unlearned words
  } catch (error) {
    console.error('Get Unlearned Words API Error:', error);
    return { success: false, message: error.response?.data?.message || '请求失败' };
  }
};

// **提交学习过的单词**
export const saveLearnedWords = async (userId, learnedWords) => {
  const token = localStorage.getItem('token');

  if (!token) {
    return { success: false, message: '未登录' };
  }

  if (!Array.isArray(learnedWords) || learnedWords.length === 0) {
    return { success: false, message: '学习记录不能为空' };
  }

  try {
    const response = await apiClient.post('/insert-user-words', {
      userId,
      learnedWords
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return response.data; // { success: true, message: "学习记录插入成功" }
  } catch (error) {
    console.error('Save Learned Words API Error:', error);
    return { success: false, message: error.response?.data?.message || '提交学习记录失败' };
  }
};


// **查询用户学习统计信息**
export const getUserStats = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 GET 请求获取学习统计信息
    const response = await apiClient.get(`/user-stats/${userId}`, {
      headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
    });

    return { success: true, stats: response.data.stats };
  } catch (error) {
    console.error('Error fetching user stats:', error);
    return { success: false, message: error.response?.data?.message || '获取统计信息失败' };
  }
};


// **查询用户单词笔记**
export const getUserNotes = async (userId, wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 GET 请求获取用户单词笔记
    const response = await apiClient.get(`/getNotes`, {
      params: { user_id: userId, word_id: wordId }, // 传递查询参数
      headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
    });

    return { success: true, notes: response.data };
  } catch (error) {
    console.error('Error fetching user notes:', error);
    return { success: false, message: error.response?.data?.message || '获取单词笔记失败' };
  }
};


// **添加用户单词笔记**
export const addNote = async (userId, wordId, noteContent) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 发送 POST 请求添加用户的单词笔记
    const response = await apiClient.post(
      '/addNote',
      { user_id: userId, word_id: wordId, note: noteContent }, // 请求体传递的参数
      {
        headers: { 'Authorization': `Bearer ${token}` } // 带上 token 进行身份验证
      }
    );

    return { success: true, message: '笔记添加成功' };
  } catch (error) {
    console.error('Error adding user note:', error);
    return { success: false, message: error.response?.data?.message || '添加笔记失败' };
  }
};

// 删除用户笔记 API
export const deleteNoteApi = async (noteId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    const response = await apiClient.delete(`/deleteNote/${noteId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('Error deleting note:', error);
    return { success: false, message: error.response?.data?.message || '删除笔记失败' };
  }
};

// 编辑笔记
export const editNoteApi = async (noteId, newContent) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    const response = await apiClient.put(`/editNote/${noteId}`,
      { note: newContent },
      {
        headers: { 'Authorization': `Bearer ${token}` }
      }
    );

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('Error updating note:', error);
    return { success: false, message: error.response?.data?.message || '更新笔记失败' };
  }
};


// 📁 src/api/signin.js

// 用户签到
export const userSignin = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.post('/signin', { user_id: userId }, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, message: response.data.message };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || '签到失败'
    };
  }
};

// 获取签到记录
export const getSigninRecords = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/signin-records/${userId}`, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, records: response.data.records };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || '获取签到记录失败'
    };
  }
};
// 退出登录更新日志
// 退出登录更新日志
export const LogoutUpdateLog = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.post(
      '/logout',
      { userId }, // 请求体传 userId
      {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
    );

    return {
      success: true,
      records: response.data.records || null,
      message: response.data.message || '退出成功'
    };
  } catch (error) {
    return {
      success: false,
      message: error.response?.data?.message || '退出失败'
    };
  }
};


// 获取用户需要复习的单词（支持分组数量）
export const getReviewWords = async (userId, limit) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/review-words', {
      params: { user_id: userId, limit },
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, words: response.data.words };
  } catch (error) {
    console.error('获取复习单词失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};
// 获取用户当前需要复习的单词数量
export const getReviewWordCount = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get('/review-word-count', {
      params: { user_id: userId },
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, count: response.data.count };
  } catch (error) {
    console.error('获取复习单词数量失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 批量更新单词的复习时间
export const updateReviewTime = async (userId, words) => {
  try {
    // console.log(userId, words, 'i看婆萨客场扑克牌萨科csaas');
    userId = parseInt(userId);
    // console.log(userId, words, 'i看婆萨客场扑克牌萨科');
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 检查必要参数是否存在
    if (!userId || !Array.isArray(words) || words.length === 0) {
      return { success: false, message: '缺少必要的参数' };
    }

    // 发送 POST 请求来更新复习时间
    const response = await apiClient.post(
      '/update-review-time',
      {
        userId,
        words
      },
      {
        headers: { 'Authorization': `Bearer ${token}` }
      }
    );

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('更新复习时间失败:', error);
    return { success: false, message: error.response?.data?.message || '服务器错误' };
  }
};


// 添加学习日志信息
export const addStudyLogDataApi = async (
  userId,
  studyDate,
  startTime,
  endTime,
  durationMinutes,
  wordCount,
  sessionType
) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) {
      return { success: false, message: '请先登录' };
    }

    // 参数校验
    if (
      !userId || !studyDate || !startTime || !endTime ||
      typeof durationMinutes !== 'number' || typeof wordCount !== 'number' || !sessionType
    ) {
      return { success: false, message: '缺少或无效的参数' };
    }

    const payload = {
      user_id: userId,
      study_date: studyDate,
      start_time: startTime,
      end_time: endTime,
      duration_minutes: durationMinutes,
      word_count: wordCount,
      session_type: sessionType
    };

    const response = await apiClient.post('/addStudyLog', payload, {
      headers: { Authorization: `Bearer ${token}` }
    });

    return { success: true, message: response.data.message };
  } catch (error) {
    console.error('添加学习日志失败:', error);
    const message = error.response?.data?.message || '服务器错误，请稍后重试';
    return { success: false, message };
  }
};


// 获取用户每个月学习单词数量
export const getStudyWordNumberInEveryMonthlyApi = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/stats/${userId}/monthly-word-count`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, stats: response.data.stats };
  } catch (error) {
    console.error('获取学习单词数量失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};


// 获取用户单词熟练度个数
export const getUserWordProficiencyDistributionApi = async (userId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/stats/${userId}/proficiency-distribution`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, stats: response.data.proficiencyStats };
  } catch (error) {
    console.error('获取学习单词数量失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};


// 用单词id获取例句
// 用单词id获取例句
export const getWordSentencesByWordIdApi = async (wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/words/${wordId}/sentences`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return { success: true, sentences: response.data.sentences };
  } catch (error) {
    console.error('获取例句失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 用单词id获取同义词和反义词
export const getSynonymsAntonymsByWordIdApi = async (wordId) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.get(`/api/words/${wordId}/synonyms-antonyms`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      synonyms: response.data.synonyms,
      antonyms: response.data.antonyms
    };
  } catch (error) {
    console.error('获取同义词/反义词失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};

// 根据用户id查询用户详细数据
export const getUserDetailsByIdApi = async (userId) => {
  // console.log(userId, '用户id');
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    // 发送 GET 请求，获取用户详细数据
    const response = await apiClient.get(`/api/users/details/${userId}`, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      user: response.data  // 返回详细的用户数据
    };
  } catch (error) {
    console.error('获取用户详细数据失败:', error);
    return { success: false, message: error.response?.data?.message || '获取失败' };
  }
};
// 更新用户详细数据（PUT 请求）
export const updateUserDetailsByIdApi = async (userId, updatedData) => {
  try {
    const token = localStorage.getItem('token');
    if (!token) return { success: false, message: '请先登录' };

    const response = await apiClient.put(`/api/users/details/${userId}`, updatedData, {
      headers: { 'Authorization': `Bearer ${token}` }
    });

    return {
      success: true,
      message: response.data.message
    };
  } catch (error) {
    console.error('更新用户详细数据失败:', error);
    return { success: false, message: error.response?.data?.message || '更新失败' };
  }
};
// 获取当天错误最多的三个单词及其详细数据
export const getMostErrorWordDataApi = async () => {
  try {
    const response = await apiClient.get('/api/most-error-words');  // 正确的请求路径
    return response.data;
  } catch (error) {
    console.error('获取单词数据失败:', error);
    return {
      success: false,
      message: error.response?.data?.message || '获取单词数据失败',
    };
  }
};
















